package com.koro.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.koro.DTO.FindJobInfoDTO;
import com.koro.DTO.JobInfoDTO;
import com.koro.constant.ScheduleConstants;
import com.koro.entity.JobInfo;
import com.koro.exception.job.TaskException;
import com.koro.mapper.JobInfoMapper;
import com.koro.service.JobInfoService;
import com.koro.text.Convert;
import com.koro.tool.StringUtils;
import com.koro.utils.CronUtils;
import com.koro.utils.ScheduleUtils;
import com.koro.vo.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class JobInfoServiceImpl implements JobInfoService {

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private JobInfoMapper jobInfoMapper;

    @Value("${spring.application.name}")
    private String serviceName;

    @Override
    public void addCronJob(JobInfoDTO dto) {
        if(!findCheckCronExpressionIsValid(dto.getCronExpression())) {
            throw new BaseException("Cron格式不正确..");
        }
        if(!checkServiceName(dto.getJobGroup())) {
            throw new BaseException("服务不存在..");
        }
        JobInfo jobInfo = new JobInfo();
        BeanUtils.copyProperties(dto,jobInfo);
        jobInfoMapper.insert(jobInfo);
        try {
            ScheduleUtils.createScheduleJob(scheduler, jobInfo);
        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        } catch (TaskException e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 项目启动时，初始化定时器
     * 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        List<JobInfo> jobInfos = jobInfoMapper.selectList(Wrappers.<JobInfo>lambdaQuery()
                .eq(JobInfo::getJobGroup, serviceName));
        for (JobInfo job : jobInfos) {
            updateSchedulerJob(job, job.getJobGroup());
        }
    }

    /**
     * 获取quartz调度器的计划任务列表
     *
     * @return
     */
    @Override
    public List<JobInfo> queryList(FindJobInfoDTO dto) {
        return jobInfoMapper.selectList(Wrappers.<JobInfo>lambdaQuery()
                .eq(StringUtils.isNotEmpty(dto.getJobName()), JobInfo::getJobName, dto.getJobName())
                .eq(StringUtils.isNotEmpty(dto.getJobGroup()), JobInfo::getJobGroup, dto.getJobGroup())
                .eq(StringUtils.isNotEmpty(dto.getStatus()), JobInfo::getStatus, dto.getStatus())
                .orderByDesc(JobInfo::getJobId)
             //   .last(SqlUtil.getLimitSql(dto.getCurrentPage(), dto.getShowCount()))
        );
    }

    @Override
    public Long queryTotal(FindJobInfoDTO dto) {
        return jobInfoMapper.selectCount(Wrappers.<JobInfo>lambdaQuery()
                .eq(StringUtils.isNotEmpty(dto.getJobName()), JobInfo::getJobName, dto.getJobName())
                .eq(StringUtils.isNotEmpty(dto.getJobGroup()), JobInfo::getJobGroup, dto.getJobGroup())
                .eq(StringUtils.isNotEmpty(dto.getStatus()), JobInfo::getStatus, dto.getStatus())
        );
    }

    /**
     * 通过调度任务ID查询调度信息
     *
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public JobInfo findJobById(Long jobId) {
        return jobInfoMapper.selectById(jobId);
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    public void updateJobStatusToPause(JobInfo job) {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        try {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
        jobInfoMapper.updateById(job);
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    public void updateJobStatusToResume(JobInfo job) {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        try {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
        jobInfoMapper.updateById(job);
    }


    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    public void deleteJob(JobInfo job) {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        if (null != jobInfoMapper.selectById(jobId)) {
            try {
                scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
            } catch (SchedulerException e) {
                e.printStackTrace();
                throw new BaseException(e.getMessage());
            }
        }
        jobInfoMapper.deleteById(jobId);
    }

    /**
     * 批量删除调度信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public void deleteJobByIds(String ids) {
        Long[] jobIds = Convert.toLongArray(ids);
        for (Long jobId : jobIds) {
            JobInfo job = jobInfoMapper.selectById(jobId);
            deleteJob(job);
        }
    }

    @Override
    public void delete(Long id) {
        JobInfo job = jobInfoMapper.selectById(id);
        if (null != job) {
            deleteJob(job);
        }
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    public void updateStatus(JobInfo job) {
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            updateJobStatusToResume(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            updateJobStatusToPause(job);
        }
    }

    /**
     * 立即运行任务
     */
    @Override
    public void executeRun(Long id) {
        JobInfo properties = jobInfoMapper.selectById(id);
        String jobGroup = properties.getJobGroup();
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        try {
            scheduler.triggerJob(ScheduleUtils.getJobKey(id, jobGroup), dataMap);
        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 更新任务的时间表达式
     *
     * @param dto 调度信息
     */
    @Override
    public void updateJob(JobInfoDTO dto) {
        if (!findCheckCronExpressionIsValid(dto.getCronExpression())) {
            throw new BaseException("Cron执行表达式不符合规范!");
        }
        if (!checkServiceName(dto.getJobGroup())) {
            throw new BaseException("服务不存在!");
        }

        JobInfo properties = jobInfoMapper.selectById(dto.getJobId());
        JobInfo job = new JobInfo();
        BeanUtils.copyProperties(dto, job);
        if (!properties.getCronExpression().equals(dto.getCronExpression())) {
            try {
                updateSchedulerJob(job, properties.getJobGroup());
            } catch (SchedulerException e) {
                e.printStackTrace();
                throw new BaseException(e.getMessage());
            } catch (TaskException e) {
                e.printStackTrace();
                throw new BaseException(e.getMessage());
            }
        }
        jobInfoMapper.updateById(job);
    }

    /**
     * 更新任务
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(JobInfo job, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }




    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean findCheckCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }


    private boolean checkServiceName(String name) {

        List<String> serviceList = new ArrayList<>();
        serviceList.add("mall-admin");
        serviceList.add("shop-portal");
        serviceList.add("shop-service-users");
        serviceList.add("shop-service-orders");
        serviceList.add("shop-service-goods");
        if (serviceList.contains(name)) {
            return true;
        }
        return false;
    }

    public void testQuartz(){
        System.out.println(serviceName + "执行定时任务");
    }
}

